package com.android.duininsuoai.fragment.group;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.duininsuoai.R;
import com.android.duininsuoai.activity.GoodsDetailActivity;
import com.android.duininsuoai.activity.ImagePagerActivity;
import com.android.duininsuoai.adapt.MyDateViewHolder;
import com.android.duininsuoai.fragment.BaseLazyFragment;
import com.android.duininsuoai.model.auction.AuctionRecentlyOrder;
import com.android.duininsuoai.model.auction.Orderts_HistoryData;
import com.android.duininsuoai.model.auction.Orderts_HistoryDataCallback;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.LoginState;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.view.CustomViewpager;
import com.android.duininsuoai.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.android.duininsuoai.activity.ImagePagerActivity.EXTRA_IMAGE_CURRENTID;
import static com.android.duininsuoai.activity.ImagePagerActivity.EXTRA_IMAGE_URLS;

/**
 * Created by Administrator on 2017/11/3.
 */

public class Fragment_Orderts_History2 extends BaseLazyFragment {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;

    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    private FragmentActivity mcontext;
    private View view;
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private boolean networkConnected;
    private AdaptList adapter;
    private ArrayList<Orderts_HistoryData.DataBean.ListBean> listdata  = new ArrayList<>();;
    private CustomViewpager viewpager;
    private GoodsDetailActivity mActivity;
    private int mid;
    private int page =1;
    private String token;
    private int lastposition =0;
    private String auction_id;
    /**
     * 最新成交
     */


    public Fragment_Orderts_History2() {


    }

    public static Fragment_Orderts_History2 newInstance() {
        Fragment_Orderts_History2 fragment = new Fragment_Orderts_History2();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }
    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 2:
                    page = page+1;
                    GetDataListData();
                    break;
            }
        };

    };

    @Override
    protected void initPrepare() {

        ReFreshData();
    }

    private void initRecycle() {
        adapter = new AdaptList(mcontext, listdata,"");
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);

    }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {

        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {

            GetDataListData();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_recycle_pastedturnover, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
        }
        return view;
    }

    private void ReFreshData() {

    }


    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        GetDataListData();


    }





    /**
     * 商品列表
     */
    private void GetDataListData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        final String address = "https://jm.lnest.cc/api/" + ConstantsUrl.ACUTIONCOMMENT ;
        HashMap<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("size","10");
        map.put("mid",mid+"");
        MyLog.e("auction_id",auction_id);
        MyLog.e("mid",mid+"");

        if (networkConnected) {

            HttpUtils.get(address,map, new Orderts_HistoryDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(Orderts_HistoryData response, int id) {

                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata = new ArrayList<>();
                        if (response.getData().getList() != null&&response.getData().getList().size()>0) {

                            for (int i = 0; i < response.getData().getList().size(); i++) {
                                listdata.add(new Orderts_HistoryData.DataBean.ListBean(Orderts_HistoryData.DataBean.ListBean.THREE, response.getData().getList().get(i).getId()
                                        , response.getData().getList().get(i).getThumbs(), response.getData().getList().get(i).getMid()
                                        ,  response.getData().getList().get(i).getContent(),response.getData().getList().get(i).getStar()
                                        , response.getData().getList().get(i).getC_time(),response.getData().getList().get(i).getUsername()
                                        , response.getData().getList().get(i).getTitle(),response.getData().getList().get(i).getPhoto()));
                            }
                            adapter.addData(lastposition,listdata);
                            lastposition = lastposition+response.getData().getList().size();

                        } else {
                            noData.setVisibility(View.VISIBLE);

                        }
                    }
                }
            });
        }else {
            noData.setVisibility(View.VISIBLE);
            noDataTv.setVisibility(View.VISIBLE);
            ObjectUtils.toast(mcontext, "网络未连接");

        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<Orderts_HistoryData.DataBean.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptList(FragmentActivity context, List<Orderts_HistoryData.DataBean.ListBean> data, String type) {
            super(data);
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionRecentlyOrder.DataBean.ListBean.THREE, R.layout.item_ordertoshare_ry);
        }



        @Override
        protected void convert(MyDateViewHolder holder, final Orderts_HistoryData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case AuctionRecentlyOrder.DataBean.ListBean.THREE:

                    //判断list里面是否含有该holder，没有就增加
                    //因为list已经持有holder的引用，所有数据自动会改变
                    ObjectUtils.photoCircle(mContext, mainlistdata.getPhoto(), ((ImageView) holder.getView(R.id.toastpic_comsumer)));
                    int time = Integer.parseInt(mainlistdata.getC_time());
                    long msl=(long)time*1000;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String text = format.format(msl);
                    holder.setText(R.id.recently_day,text);
                    holder.setText(R.id.detail_phonenumber,text);
                    holder.setText(R.id.detail_phonenumber, mainlistdata.getUsername());
                    holder.setText(R.id.statement_title, mainlistdata.getTitle());
                    holder.setText(R.id.statement_content, mainlistdata.getContent());
                    //水平滚动列表
                    NestFullListView tabrow = (NestFullListView) holder.getView(R.id.main_fragment_grid_sort1);
                    //        //动态设置选项卡宽度，超过2个可以滑动查看
                    DisplayMetrics metrics = new DisplayMetrics();
                    mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                    String[] tbs = new String[mainlistdata.getThumbs().size()-1];
                    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(metrics.widthPixels / 2, LinearLayout.LayoutParams.MATCH_PARENT);
                    tabrow.setAdapter(new NestFullListViewAdapter<String>(R.layout.item_detail_orderts_grid, mainlistdata.getThumbs()) {
                        @Override
                        public void onBind(int position, String testBean, NestFullViewHolder holder) {

                            ObjectUtils.photo2(mcontext, testBean,((ImageView) holder.getView(R.id.item_grid_detail_like_img)));

                        }

                    });

                    tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                        @Override
                        public void onItemClick(NestFullListView nestFullListView, View view, int pos) {

                            Intent intent = new Intent(getActivity(),ImagePagerActivity.class);
                            //intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "");
                            Bundle b=new Bundle();
                            String a[] = new String[mainlistdata.getThumbs().size()];
                            b.putStringArray(EXTRA_IMAGE_URLS,mainlistdata.getThumbs().toArray(a));
                            intent.putExtras(b);
                            intent.putExtra(EXTRA_IMAGE_CURRENTID,pos);
                            startActivity(intent);
                            //  ObjectUtils.ToDetailActivity(mcontext, 1, ta_insert.get(taposition / 4 - 1).getApply_list().get(pos).getGoods_id(), "");
                        }
                    });


                    break;

            }
        }


    }

}